import { useEffect, useState } from "react";
import { Button, Card, Drawer, Form, Input, Space, Select, Spin } from "antd";
import type { ColumnsType } from "antd/es/table";
import defectService, {
  type PageListReq,
} from "@/api/services/qms/defectService";
import indexService from "@/api/services/qms/indexService";
import type { QmsDefect } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import CustomTable from "@/components/grid/CustomTable";

const { TextArea } = Input;

export default function QmsDefectPage() {
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    defectCode: undefined,
    defectName: undefined,
    indexId: undefined,
    defectLevel: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<QmsDefect[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<QmsDefect | null>(null);
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);
  const [indexOptions, setIndexOptions] = useState<
    { value: React.Key; label: string }[]
  >([]);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  useEffect(() => {
    fetchIndexList();
  }, []);

  const defectLevelOptions = useDictionary("qms_defect_level");

  const columns: ColumnsType<QmsDefect> = [
    {
      title: "缺陷编码",
      width: 120,
      key: "defectCode",
      dataIndex: "defectCode",
    },
    {
      title: "缺陷描述",
      width: 120,
      key: "defectName",
      dataIndex: "defectName",
    },
    {
      title: "检测项",
      width: 120,
      key: "indexName",
      dataIndex: "indexName",
    },
    {
      title: "缺陷等级",
      width: 120,
      key: "defectLevel",
      dataIndex: "defectLevel",
      render: (_, record) => (
        <TableDictTag
          dictCode="qms_defect_level"
          value={record.defectLevel ?? ""}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    defectService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  //加载岗位列表
  const fetchIndexList = async () => {
    try {
      const indexs = await indexService.list();
      const options = indexs.map((index) => ({
        value: index.id,
        label: index.indexName,
      }));
      setIndexOptions(options);
    } catch (error) {
      console.error("获取检验项列表失败:", error);
      toast.error("获取检验项列表失败");
      return [];
    }
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (qmsDefect: QmsDefect) => {
    setEditingData(qmsDefect);
    form.setFieldsValue(qmsDefect);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (qmsDefect: QmsDefect) => {
    setEditingData(qmsDefect);
    form.setFieldsValue(qmsDefect);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: QmsDefect) => {
    try {
      setSubmitLoading(true);

      const data = {
        ...values,
        id: editingData?.id,
      };
      if (editingData) {
        await defectService.update(data);
        toast.success("更新缺陷成功");
      } else {
        await defectService.add(data);
        toast.success("创建缺陷成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  //提交表单数据
  const handleNextAdd = async () => {
    try {
      setSubmitLoading(true);
      const values = form.getFieldsValue();
      
      const data = {
        ...values,
        id: editingData?.id,
      };
      await defectService.add(data);
      toast.success("创建缺陷成功");

      setEditingData(null);
      form.resetFields();

      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await defectService.remove(selectedRowKeys);
      toast.success("删除常见缺陷成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="defectCode" label="缺陷编码">
            <Input placeholder="请输入缺陷编码" allowClear />
          </Form.Item>
          <Form.Item name="defectName" label="缺陷描述">
            <Input placeholder="请输入缺陷描述" allowClear />
          </Form.Item>
          <Form.Item name="indexId" label="检测项类型">
            <Select
              showSearch
              options={indexOptions}
              placeholder="请选择检测项"
              allowClear
              optionFilterProp="label"
              filterOption={(input, option) =>
                (option?.label ?? "")
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
              style={{ width: 170 }}
            />
          </Form.Item>
          <Form.Item name="defectLevel" label="缺陷等级">
            <Input placeholder="请输入缺陷等级" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          current={queryParams.page}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          pageSize={queryParams.pageSize}
          onPageChange={handlePageChange}
          onRefresh={fetchPageList}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑常见缺陷" : "新增常见缺陷"}
        width={480}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <>
                {!editingData && (
                  <Button type="primary" onClick={() => handleNextAdd()}>
                    继续添加
                  </Button>
                )}
                <Button type="primary" onClick={() => form.submit()}>
                  保存并关闭
                </Button>
              </>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Form.Item
            name="defectCode"
            label="缺陷编码"
            rules={[
              {
                required: true,
                message: "请填写缺陷编码",
              },
            ]}
          >
            <Input placeholder="请输入缺陷编码" allowClear />
          </Form.Item>

          <Form.Item
            name="defectName"
            label="缺陷描述"
            rules={[
              {
                required: true,
                message: "请填写缺陷描述",
              },
            ]}
          >
            <TextArea />
          </Form.Item>

          <Form.Item
            name="indexId"
            label="检测项"
            rules={[
              {
                required: true,
                message: "请填写检测项",
              },
            ]}
          >
            <Select
              showSearch
              options={indexOptions}
              placeholder="请选择检测项"
              allowClear
              optionFilterProp="label"
              filterOption={(input, option) =>
                (option?.label ?? "")
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>

          <Form.Item
            name="defectLevel"
            label="缺陷等级"
            rules={[
              {
                required: true,
                message: "请填写缺陷等级",
              },
            ]}
          >
            <Select options={defectLevelOptions} allowClear />
          </Form.Item>

          <Form.Item name="remark" label="备注">
            <TextArea />
          </Form.Item>
        </Form>
      </Drawer>
    </Spin>
  );
}
